import { computed, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { defineStore } from 'pinia'
import { io } from "socket.io-client";

export const useCounterStore = defineStore('chat', () => {
  const router = useRouter()
  //聊天室
  const state = reactive({
    username: router.currentRoute.value.query.username,
    userList: [],
    targetUser: null,
    msgText: "",
    messageBox: {},
    toUsername:null,
  });

  let socket;
  const connectSocket = () => {
    if(!socket && state.username){
      socket = io("http://localhost:4000",{
        query: {
          username: state.username
        }
      });
      socket.on("online", (data) => {
        console.log(data.userList,'userList--pinia');
        state.userList = data.userList;
      });

      
    
      socket.on("receive", (data) => {
        console.log(data,'receive--pinia');
        
        appendMessage(data);
      });


      socket.on('imageMessage', (data) => {
        console.log(data,'imageMessage--pinia');
        
        console.log('Received image message: ', data);
        const imgBaseUrl = "http://localhost:3000/uploads";
        const imageName = data.path.split("\\").pop();
        const imageUrl = imgBaseUrl + '/' + imageName;
        console.log('Received image URL:', imageUrl);
        appendMessage({
          fromUsername: data.fromUsername,
          toUsername: data.toUsername,
          msg: `<img src="${imageUrl}" />`,
          dateTime: data.dateTime,
        });
    });
    
      socket.on("error", (err) => {
        console.log(err);
      });


    }
  }
  

  const selectUser = (userInfo) => {
    console.log(userInfo,'pinia'); 
    state.targetUser = userInfo;
  };

  const sendMessage = (value) => {
    console.log(value,'111');

    if (!value) return;
    console.log(222);
    
    appendMessage({
      fromUsername: state.username,
      toUsername: state.targetUser.username,
      msg: value,
      dateTime: new Date().getTime(),
    });

    socket.emit("send", {
      fromUsername: state.username,
      toUsername: state.targetUser.username,
      targetId: state.targetUser.id,
      msg: value,
    });
    console.log(333);
    
  };

  
  
  function appendMessage(msg) {
    console.log('Appending message:', msg); 
    !state.messageBox[state.username] && (state.messageBox[state.username] = []);
    state.messageBox[state.username].push(msg);
  }

  router.isReady().then(connectSocket)

  return {
    state,
    selectUser,
    sendMessage
  }
})



